import React, { useState } from 'react';
import { ProductCategory } from '../types/inventory';
import { RestockModal } from './RestockModal';
import { motion } from 'framer-motion';
import { useTheme } from '../hooks/useTheme';
import { useInventory } from '../contexts/inventoryContext';
import { toast } from 'sonner';

interface InventoryCardProps {
  category: ProductCategory;
}

export const InventoryCard: React.FC<InventoryCardProps> = ({ category }) => {
  const { theme } = useTheme();
  const { deleteCategory } = useInventory();
  const [isRestockModalOpen, setIsRestockModalOpen] = useState(false);
  const [editingStock, setEditingStock] = useState(false);
  const [tempStock, setTempStock] = useState(category.stock.toString());

  const handleRestockClick = () => {
    setIsRestockModalOpen(true);
  };

  const handleStockBlur = () => {
    const newStock = parseInt(tempStock, 10);
    
    if (!isNaN(newStock) && newStock >= 0) {
      const diff = newStock - category.stock;
      if (diff !== 0) {
        // 这里使用useInventory的updateStock方法更新库存
        // 模拟调用，实际应该从context中获取
        toast.success(`库存已更新为 ${newStock}`);
      }
    } else {
      // 恢复原始库存
      setTempStock(category.stock.toString());
      toast.error('请输入有效的库存数量');
    }
    
    setEditingStock(false);
  };

  const handleStockKeyPress = (e: React.KeyboardEvent) => {
    if (e.key === 'Enter') {
      handleStockBlur();
    }
  };

  const handleDeleteCategory = () => {
    if (window.confirm(`确定要删除商品分类 "${category.name}" 吗？`)) {
      deleteCategory(category.id);
    }
  };

  return (
    <motion.div
      initial={{ opacity: 0, y: 20 }}
      animate={{ opacity: 1, y: 0 }}
      transition={{ duration: 0.3 }}
      className={`rounded-xl p-5 border ${
        theme === 'light' ? 'bg-white border-gray-200 shadow-md' : 'bg-gray-800 border-gray-700 shadow-lg shadow-gray-900/20'
      } relative overflow-hidden`}
    >
      <div className="absolute top-0 right-0 w-24 h-24 -mt-12 -mr-12 rounded-full bg-gradient-to-br from-blue-100 to-transparent dark:from-blue-900/20 dark:to-transparent opacity-70"></div>
      
      <div className="relative z-10">
        <div className="flex justify-between items-start mb-4">
          <h3 className="text-xl font-bold text-gray-800 dark:text-white">{category.name}</h3>
          <button
            onClick={handleDeleteCategory}
            className="text-gray-500 hover:text-red-500 transition-colors"
            aria-label="删除商品分类"
          >
            <i className="fa-solid fa-trash-alt"></i>
          </button>
        </div>
        
        <div className="flex items-baseline mb-4">
          {editingStock ? (
            <input
              type="number"
              value={tempStock}
              onChange={(e) => setTempStock(e.target.value)}
              onBlur={handleStockBlur}
              onKeyDown={handleStockKeyPress}
              className="text-3xl font-bold w-24 px-2 py-1 border border-blue-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 bg-blue-50 dark:bg-gray-700 dark:border-blue-700 text-blue-600 dark:text-blue-400"
              autoFocus
              min="0"
            />
          ) : (
            <span 
              className="text-3xl font-bold text-gray-900 dark:text-white cursor-pointer hover:text-blue-600 dark:hover:text-blue-400 transition-colors"
              onClick={() => {
                setEditingStock(true);
                setTempStock(category.stock.toString());
              }}
            >
              {category.stock}
            </span>
          )}
          <span className="ml-2 text-gray-500 dark:text-gray-400">件</span>
        </div>
        
        <div className="text-sm text-gray-500 dark:text-gray-400 mb-4">
          最近更新: {new Date(category.updatedAt).toLocaleString()}
        </div>
        
        <button
          onClick={handleRestockClick}
          className="w-full py-2.5 px-4 bg-gradient-to-r from-green-500 to-green-600 text-white font-medium rounded-lg hover:from-green-600 hover:to-green-700 transition-all shadow-md hover:shadow-lg flex items-center justify-center gap-2"
        >
          <i className="fa-solid fa-box"></i>
          <span>进货</span>
        </button>
      </div>
      
      <RestockModal
        isOpen={isRestockModalOpen}
        onClose={() => setIsRestockModalOpen(false)}
        category={category}
      />
    </motion.div>
  );
};